import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:wan_android_flutter/http/dio_instance.dart';
import 'package:wan_android_flutter/repository/api.dart';
import '../../repository/datas/home_banner_data.dart';
import '../../repository/datas/home_list_data.dart';

// HomeViewModel类，用于管理首页的Banner数据
class HomeViewModel with ChangeNotifier {
  int pageCount = 1;
  List<HomeBannerData>? bannerList; // 用于存储Banner数据的列表，初始为null
  List<HomeListItemData>? listData = []; // 用于存储首页文章列表数据的列表，初始为null

  ///获取首页Banner数据
  // 异步方法，用于获取Banner数据
  Future getBanner() async {
    //Future函数是有回调的
    List<HomeBannerData>? list = await Api.instance.getBanner();
    bannerList = list ?? []; // 如果不为空，将数据赋值给bannerList
    // 通知监听器，数据已经更新
    notifyListeners();
  }

  Future initListData(bool loadMore, {ValueChanged<bool>? callback}) async {
    if (loadMore) {
      pageCount++;
    } else {
      pageCount = 1;
      listData?.clear();
    }
    //选获取置顶数据
    getTopList(loadMore).then((topList) {
      if (!loadMore) {
        listData?.addAll(topList ?? []);
      }

      //再获取首页列表
      getHomeList(loadMore).then((allList) {
        listData?.addAll(allList ?? []);
        //刷新
        notifyListeners();

        //回调出去
        callback?.call(loadMore);
      });
    });
  }

  ///获取首页文章列表
  Future<List<HomeListItemData>?> getHomeList(bool loadMore) async {
    List<HomeListItemData>? list = await Api.instance.getHomeList("$pageCount");
    if (list != null && list.isNotEmpty) {
      return list;
    } else {
      if (loadMore && pageCount > 0) {
        pageCount--;
      }
      return [];
    }
  }

  ///获取首页置顶数据
  Future<List<HomeListItemData>?> getTopList(bool loadMore) async {
    if (loadMore) {
      return [];
    } else {
      List<HomeListItemData>? list = await Api.instance.getHomeTopList();
      return list;
    }
  }

  ///收藏文章
  Future collect(String? id, int index) async {
    bool? success = await Api.instance.collect(id);
    if (success == true) {
      listData?[index].collect = true;
      notifyListeners();
    }
  }

  ///收藏文章
  Future unCollect(String? id, int index) async {
    bool? success = await Api.instance.unCollect(id);
    if (success == true) {
      listData?[index].collect = false;
      notifyListeners();
    }
  }
}
